package com.kedacom.freedomLabel.viewmodel;


import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.OnLifecycleEvent;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.base.UserCache;
import com.kedacom.freedomLabel.initdata.bean.CategoryNewBean;
import com.kedacom.freedomLabel.initdata.bean.MachineNumber;
import com.kedacom.freedomLabel.initdata.bean.Post;
import com.kedacom.freedomLabel.initdata.bean.RubbishBean;
import com.kedacom.freedomLabel.initdata.dao.CategoryNewDao;
import com.kedacom.freedomLabel.initdata.dao.PostDao;
import com.kedacom.freedomLabel.initdata.dao.RubbishDao;
import com.kedacom.freedomLabel.label.TemplateManager;
import com.kedacom.freedomLabel.model.annotation.ItemCategory;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.BusinessCount;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Config;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.bean.Product;
import com.kedacom.freedomLabel.model.bean.ProductCount;
import com.kedacom.freedomLabel.model.bean.Template;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.Converters;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.BusinessDao;
import com.kedacom.freedomLabel.model.db.dao.CategoryDao;
import com.kedacom.freedomLabel.model.db.dao.ConfigDao;
import com.kedacom.freedomLabel.model.db.dao.ItemDao;
import com.kedacom.freedomLabel.model.db.dao.ProductDao;
import com.kedacom.freedomLabel.model.db.dao.TemplateDao;
import com.kedacom.freedomLabel.utils.log.LLog;
import com.kedacom.freedomLabel.view.activity.ScaleActivity;
import com.kedacom.lego.mvvm.ObservableLiveDataField;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScaleViewModel extends BaseViewModel {

    public MutableLiveData<Category> mLiveDataCategory = new MutableLiveData<>();

    // 是否归零
    public ObservableLiveDataField<Boolean> isZero = new ObservableLiveDataField<>(false);
    // 是否稳定
    public ObservableLiveDataField<Boolean> isStable = new ObservableLiveDataField<>(false);

    // 显示的重量
    public ObservableLiveDataField<String> displayWeight = new ObservableLiveDataField<>("0.000");

    // 显示的扣重
    public ObservableLiveDataField<String> displayPreTare = new ObservableLiveDataField<>("0.000");

    // 显示的毛重
    public ObservableLiveDataField<String> displayGrossWeight = new ObservableLiveDataField<>("0.000");

    // 是否是称重模式
    public ObservableLiveDataField<Boolean> isWeightMode = new ObservableLiveDataField<>(true);

    // 称的单位显示
    public ObservableLiveDataField<String> displayUnit = new ObservableLiveDataField<>();

    // 主界面显示的计数
    public ObservableLiveDataField<BusinessCount> businessCount = new ObservableLiveDataField<>();

    // 主界面显示的计数
    public ObservableLiveDataField<ProductCount> productCount = new ObservableLiveDataField<>();

    public ObservableLiveDataField<Boolean> showProductPlu = new ObservableLiveDataField<>(false);

//    public ObservableLiveDataField<List<Product>> allProductList = new ObservableLiveDataField<>();

    /**
     * 称重状态
     * -1 低于下限 ；0数据正常；1高于上限
     */
    public ObservableLiveDataField<Integer> weightStatus = new ObservableLiveDataField<>(100);


    public ScaleViewModel() {

    }

    public void getProductItemInfo(String groupUUID, String groupName) {
        CategoryDao dao = AppDatabase.getInstance().categoryDao();
        DataLoader.get(dao, groupUUID, groupName, new DataCallback<List<Category>>() {
            @Override
            public void success(@Nullable List<Category> data) {
                if (data != null && data.size() > 0) {
                    Category category = data.get(0);
                    mLiveDataCategory.setValue(category);
                }
            }

            @Override
            public void error(@Nullable String errorMessage) {
                mLiveDataCategory.setValue(null);
                showToast(errorMessage, TOAST_WARNING);
            }
        });
    }

    public void getItemByItemCategory(String itemCategory) {
        ItemDao dao = AppDatabase.getInstance().itemDao();
        DataLoader.get(dao, itemCategory, new DataCallback<List<Item>>() {
            @Override
            public void success(@Nullable List<Item> data) {

            }

            @Override
            public void error(@Nullable String errorMessage) {

            }
        });
    }

    // 保存称重记录
    public void saveRecord(List<RubbishBean> rubbishBeanList) {
        RubbishDao dao = AppDatabase.getInstance().getRubbishDao();
        DataLoader.save(dao, rubbishBeanList, new DataCallback<List<RubbishBean>>() {
            @Override
            public void success(@Nullable List<RubbishBean> data) {
                updateMainCount();
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast(errorMessage, TOAST_ERROR);
            }
        });
    }

    public void saveRecordProduct(Post post) {
        PostDao dao = AppDatabase.getInstance().getPostDao();
        DataLoader.save(dao, post, new DataCallback<Post>() {
            @Override
            public void success(@Nullable Post data) {
                updateMainProductCount();
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast(errorMessage, TOAST_ERROR);
            }
        });
    }


    // 更新产品信息
    public void updateProductInfo(Product product) {
        ProductDao dao = AppDatabase.getInstance().productDao();
        DataLoader.update(dao, product);
    }

    public void updateMainProductCount() {
        ConfigDao dao = AppDatabase.getInstance().configDao();
        DataLoader.get(dao, "app_start_time", new DataCallback<List<Config>>() {
            @Override
            public void success(@Nullable List<Config> data) {
                try {
                    if (data != null && data.size() > 0) {
                        AppExecutors.getInstance().queryIO()
                                .submit(() ->{
                                    ProductCount count =  AppDatabase.getInstance()
                                            .getPostDao()
                                            .getBusiness(Long.parseLong(data.get(0).configValue));
                                    productCount.set(count);
                                });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LLog.error(Log.getStackTraceString(e));
                }
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast(errorMessage, TOAST_ERROR);
            }
        });
    }


    // 更新首页累计和总计
    public void updateMainCount() {
        ConfigDao dao = AppDatabase.getInstance().configDao();
        DataLoader.get(dao, "app_start_time", new DataCallback<List<Config>>() {
            @Override
            public void success(@Nullable List<Config> data) {
                try {
                    if (data != null && data.size() > 0) {
                        AppExecutors.getInstance().queryIO()
                                .submit(() ->{
                                    ProductCount count =  AppDatabase.getInstance()
                                            .getRubbishDao()
                                            .getBusiness(Long.parseLong(data.get(0).configValue));
                                    productCount.set(count);
                                });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LLog.error(Log.getStackTraceString(e));
                }
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast(errorMessage, TOAST_ERROR);
            }
        });
    }

//    public void getAllProduct() {
//        AppExecutors.getInstance().queryIO()
//                .submit(()->{
//                   List<Product> products =  AppDatabase.getInstance().productDao()
//                            .get();
//                    allProductList.set(products);
//                });
//    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void updateLocalCustomColumnNames() {
        UserCache.customColumnNames = Converters.sDefaultColumnNames;
        LLog.debug("ID自定义名称更新成功 " + new Gson().toJson(UserCache.customColumnNames));
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void countTemplateCount() {
        createTemplateData();
    }

    private void createTemplateData() {
        // prepare company information
        TemplateManager.CompanyPosition companyPosition = new TemplateManager.CompanyPosition();
        companyPosition.name = new Template.Position(11, 11);
        companyPosition.contactNumber = new Template.Position(12, 12);
        companyPosition.faxNumber = new Template.Position(13, 13);
        companyPosition.address = new Template.Position(14, 14);

        // prepare order information
        TemplateManager.OrderPosition orderPosition = new TemplateManager.OrderPosition();
        orderPosition.batch = new Template.Position(8, 8);
        orderPosition.serial = new Template.Position(9, 9);
        orderPosition.time = new Template.Position(10, 10);

        String templateName6030 = TemplateManager.getTemplateName(0);
        String templateName6040 = TemplateManager.getTemplateName(1);

        // init using label-template
        Template template6040 = new TemplateManager.Builder(60, 40)
                .addTitle(0, 0)
                .addQR(1, 1)
                .addID1(2, 2)
                .addID2(3, 3)
                .addID3(4, 4)
                .addID4(5, 5)
                .addID5(6, 6)
                .addID6(7, 7)
                .addCompanyInformation(companyPosition)
                .addOrderInformation(orderPosition)
                .build(templateName6040);
        Template template6030 = new TemplateManager.Builder(60, 30)
                .addTitle(0, 0)
                .addQR(1, 1)
                .addID1(2, 2)
                .addID2(3, 3)
                .addID3(4, 4)
                .addID4(5, 5)
                .addID5(6, 6)
                .addID6(7, 7)
                .addCompanyInformation(companyPosition)
                .addOrderInformation(orderPosition)
                .build(templateName6030);

        List<Template> templateList =new ArrayList<>();
        templateList.add(template6030);
        templateList.add(template6040);
        TemplateDao dao = AppDatabase.getInstance().templateDao();
        DataLoader.save(dao, templateList, new DataCallback<List<Template>>() {
            @Override
            public void success(@Nullable List<Template> data) {
                if (data == null) return;
                LLog.debug("打印模板生产成功");
            }

            @Override
            public void error(@Nullable String errorMessage) {
                LLog.debug("打印模板生产失败");
            }
        });

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void prepareUserCacheData() {
        ConfigDao configDao = AppDatabase.getInstance().configDao();
        DataLoader.get(configDao, new DataCallback<List<Config>>() {
            @Override
            public void success(@Nullable List<Config> data) {
                if (data != null) {
                    Map<String, String> map = new HashMap<>();
                    for (Config bean : data) {
                        map.put(bean.configKey, bean.configValue);
                    }
                    UserCache.init(map);
                    LLog.debug("用户信息读取成功");
                }
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast("用户信息读取失败", TOAST_ERROR);
                LLog.error("用户信息读取失败 " + errorMessage);
            }
        });
    }
    public void inserCategory(){

        List<CategoryNewBean> categoryNewBeanList=new ArrayList<>();
        CategoryNewBean categoryNewBean=new CategoryNewBean();
        categoryNewBean.setName("厨余垃圾");
        categoryNewBean.setInit(false);
        CategoryNewBean categoryNewBean01=new CategoryNewBean();
        categoryNewBean01.setName("其他垃圾");
        categoryNewBean01.setInit(false);
        CategoryNewBean categoryNewBean02=new CategoryNewBean();
        categoryNewBean02.setName("废纸");
        categoryNewBean02.setInit(false);
        CategoryNewBean categoryNewBean03=new CategoryNewBean();
        categoryNewBean03.setName("废塑料");
        categoryNewBean03.setInit(false);
        CategoryNewBean categoryNewBean04=new CategoryNewBean();
        categoryNewBean04.setName("废玻璃");
        categoryNewBean04.setInit(false);
        CategoryNewBean categoryNewBean05=new CategoryNewBean();
        categoryNewBean05.setName("废金属");
        categoryNewBean05.setInit(false);
        CategoryNewBean categoryNewBean06=new CategoryNewBean();
        categoryNewBean06.setName("废织物");
        categoryNewBean06.setInit(false);
        categoryNewBeanList.add(categoryNewBean);
        categoryNewBeanList.add(categoryNewBean01);
        categoryNewBeanList.add(categoryNewBean02);
        categoryNewBeanList.add(categoryNewBean03);
        categoryNewBeanList.add(categoryNewBean04);
        categoryNewBeanList.add(categoryNewBean05);
        categoryNewBeanList.add(categoryNewBean06);


        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    CategoryNewDao categoryNewDao = AppDatabase.getInstance().getCategoryNewDao();
                    for(CategoryNewBean categoryNew:categoryNewBeanList){
                        List<CategoryNewBean> categoryNewBeanList1 =  categoryNewDao.get(categoryNew.name);
                        if(categoryNewBeanList1.size()==0){
                            DataLoader.save(categoryNewDao,categoryNew);
                        }

                    }
                    sendMessage("RefreshCategory",null);
                });



    }


    public void insertUser(Item user){
        Item item =new Item();
        item.category = ItemCategory.ITEM_1;
        item.number = "123456";
        item.value = "李程";

        ItemDao itemDao = AppDatabase.getInstance().itemDao();
        DataLoader.save(itemDao,user);
    }

    public void querAllMachine() {
        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    List<MachineNumber> machineNumberList = AppDatabase.getInstance().getMachineNumDao()
                            .get();
                    sendMessage("getMachineList",machineNumberList);
                });
    }

}